/**
 * Copyrights Christophe Cornu 2010, All rights reserved.
 */
package com.cctl.speaker.server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.cctl.speaker.Book;
import com.cctl.speaker.Sentence;
import com.cctl.speaker.Speaker;
import com.cctl.speaker.Speaker.Result;
import com.cctl.speaker.match.Match;
import com.cctl.speaker.match.Match1;
import com.cctl.speaker.match.Match2;

public class SpeakerServer {

	int port;
	
	Speaker speaker;
	
	public SpeakerServer(int port) {
		this.port = port;
	}
	
	public void initParser() {
		String path = "D:/chrix/work/RTC-ExpressC-Full-1.0.1-Win/workspace/Speaker/src/17489-8.txt";
		Book book = new Book();
		Map<String, String> dictionary = new HashMap<String, String>();
		Set<Sentence> sentences = new HashSet<Sentence>();
		book.parseFile(path, dictionary, sentences);
		
		speaker = new Speaker();
		speaker.book = sentences;
		speaker.dictionary = dictionary;
	}
	
	public void start() throws Exception {
		initParser();
		
		ServerSocket serversocket = new ServerSocket(port);
		System.out.println("SpeakerServer "+port+" ready");
		while (true) {
			Socket connectionsocket = serversocket.accept();
	        InetAddress client = connectionsocket.getInetAddress();
	        BufferedReader input =
	            new BufferedReader(new InputStreamReader(connectionsocket.
	            getInputStream()));
	        DataOutputStream output =
	            new DataOutputStream(connectionsocket.getOutputStream());
	        String request = input.readLine();
	        // GET /speaker/Match3/on/les/eut/etonnees HTTP/1.0
	        int queryStart = request.indexOf("/speaker/");
	        String[] words = null;
	        if (queryStart != -1) {
	        	String query = request.substring(queryStart + "/speaker/".length());
	        	int end = query.indexOf(" ");
	        	if (end != -1) {
	        		query = query.substring(0, end);
	        		words = query.split("/");
	        	}
	        }
	        System.out.println(request);
	        output.write("HTTP/1.0 200 OK\r\nConnection: close\r\nContent-Type: text/html; charset=utf-8\r\n\r\n".getBytes("UTF-8"));
	        output.write("<html><body>".getBytes("UTF-8"));
	        if (words != null) {
	        	String className = words[0];
	        	Class matchClass = Class.forName(Match.class.getPackage().getName()+"."+className);
	        	Match match = (Match)matchClass.newInstance();        	
	        	if (match != null) {
	        		String[] words2 = new String[words.length - 1];
	        		System.arraycopy(words, 1, words2, 0, words2.length);
		        	List<Result> results = speaker.getMatches(match, new Sentence(words2, speaker.dictionary, false));
		        	int a = 0;
		        	for (Result result : results) {
		        		String out = "<li>"+result.toString()+"</li>";
		        		output.write(out.getBytes("UTF-8"));
		        		if (a > 5)
		        			break;
		        	}	        		
	        	}
	        }
	        output.write("<html><body>Hi</body></html>".getBytes("UTF-8"));
	        output.close();
		}
	}
	
	public void shutdown() {}
	
	public static void main(String[] args) throws Exception {
		SpeakerServer server = new SpeakerServer(9091);
		server.start();
	}
}
